package org.example.onlineEducation.filter;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import org.example.onlineEducation.utils.JWTUtils;
import org.example.onlineEducation.utils.LoginUser;
import org.example.onlineEducation.utils.MyGrantedAuthority;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Component
public class JwtTokenAuthenticationFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("token");

        if (!StringUtils.hasText(token)){
            // 无token，继续
            filterChain.doFilter(request,response);
            return;
        }
        //解析token
        String userid = null;
        List<MyGrantedAuthority> authorities = null;
        try{
            Claims claims = JWTUtils.parseToken(token);
            userid = claims.get("id").toString();

            JSONArray jsonArray = JSONArray.parseArray((String) claims.get("sub"));
            authorities = jsonArray.toJavaList(MyGrantedAuthority.class);

            System.out.println("\n\n---------------------------------- 分 割 线 ( 上 ）----------------------------------\n"
                    +  authorities
                    + "\n---------------------------------- 分 割 线 （ 下 ）----------------------------------\n");
            System.out.println(claims);

        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("Token非法！");
        }

        //将查询到的用户信息取其账号（登录凭证）以及密码去生成一个Authentication对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userid, null, authorities);
        //将Authentication对象放进springsecurity上下文中（进行认证操作）
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request,response);

    }
}
